package com.dotstone.chipism.ui.security.fragment;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dotstone.chipism.BuildConfig;
import com.dotstone.chipism.R;
import com.dotstone.chipism.base.LazyFragment;
import com.dotstone.chipism.ui.MediaDialog;
import com.dotstone.chipism.ui.security.MediaBean;
import com.dotstone.chipism.ui.security.adapter.MediaAdapter;
import com.dotstone.chipism.ui.security.me.DeviceCameraMainActivity;
import com.dotstone.chipism.ui.security.util.Util;
import com.dotstone.chipism.util.SPUtils;
import com.lib.funsdk.support.FunPath;
import com.lib.funsdk.support.FunSupport;
import com.lib.funsdk.support.models.FunDevice;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 精彩影像
 */
public class DeviceVideoFragment extends LazyFragment {
    RadioGroup rgTitle;
    RadioButton rbPic;
    RadioButton rbVid;
    RecyclerView rvView;

    ImageView ivEdit;
    MediaAdapter mediaAdapter;
    List<MediaBean> mediaList = new ArrayList<>();
    private FunDevice mFunDevice;
    private DeviceCameraMainActivity mainActivity;
    private static final String TAG = "DeviceVideoFragment";
    private Map<String, List<MediaBean>> dayMap = new HashMap<>();
    private List<String> dayList = new ArrayList<>();
    private ProgressDialog dialog;
    boolean isAllCheck = false;
    boolean isMenuOpen = false;
    boolean isVidMode = false;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_device_camera_video;
    }

    public void onFirstUserVisible() {
        mainActivity = (DeviceCameraMainActivity) getActivity();
        String devMac = (String) SPUtils.get(getContext(), "FUN_DEVICE_MAC", "");
        mFunDevice = FunSupport.getInstance().findDeviceBySn(devMac);
        if (null == mFunDevice) {
            mainActivity.finish();
            return;
        }

        initViews();
        initListener();
        initData(MediaBean.MEDIA_PIC, FunPath.PATH_CAPTURE_TEMP);
        changDataView();
    }

    private void changDataView() {
        for (String day : dayList) {
            mediaList.add(new MediaBean(day));
            List<MediaBean> list = dayMap.get(day);
            mediaList.addAll(list);
        }
        mediaAdapter.setNewData(mediaList);

    }

    private void initData(final int dataType, final String dataPath) {
        mediaList.clear();
        dayMap.clear();
        dayList.clear();
        mediaAdapter.setNewData(mediaList);
        loadFile(dataType, dataPath);
    }

    private void loadFile(int dataType, String dataPath) {
        File[] files = getPictures(dataPath);

        for (File file : files) {
            String path = getPaths(file);
            if (path != null && path.length() > 14) {
                String name = file.getName().substring(0, 14);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                try {
                    Date curDate = sdf.parse(name);
                    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
                    String date = sdfDate.format(curDate);
                    String time = sdfTime.format(curDate);
                    if (dayMap.containsKey(date)) {
                        List<MediaBean> list = dayMap.get(date);
                        list.add(new MediaBean(dataType, time, getBitmap(path, dataType), path));
                    } else {
                        List<MediaBean> list = new ArrayList<>();
                        list.add(new MediaBean(dataType, time, getBitmap(path, dataType), path));
                        dayMap.put(date, list);
                        dayList.add(date);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initListener() {
        mediaAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (isMenuOpen) {
                    mediaAdapter.setCheck(position);
                } else {
                    if (isVidMode) {
                        openFiles(getContext(), mediaAdapter.getData().get(position).itemPath, "video/*");
                    } else {
                        openFiles(getContext(), mediaAdapter.getData().get(position).itemPath, "image/*");
                    }
                }
            }
        });

        ivEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isMenuOpen = true;
                mediaAdapter.setCheckVisible(true);
                showDialog();
            }
        });

        rgTitle.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                showProgress("正在加载中");
                switch (i) {
                    case R.id.rb_pic:
                        initData(MediaBean.MEDIA_PIC, FunPath.PATH_CAPTURE_TEMP);
                        changDataView();
                        isVidMode = false;
                        break;
                    case R.id.rb_vid:
                        initData(MediaBean.MEDIA_VID, FunPath.PATH_VIDEO);
                        changDataView();
                        isVidMode = true;
                        break;
                }
                dismissProgress();
            }
        });
    }


    private void showDialog() {
        mainActivity.llMenu.setVisibility(View.VISIBLE);
        mainActivity.tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mediaAdapter.setCheckVisible(false);
                mainActivity.llMenu.setVisibility(View.GONE);
                isMenuOpen = false;
            }
        });
        mainActivity.tvSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isAllCheck = !isAllCheck;
                mediaAdapter.setAllCheck(isAllCheck);
            }
        });
        mainActivity.tvDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<MediaBean> list = mediaAdapter.getCheckList();
                for (MediaBean mediaBean : list) {
                    File file = new File(mediaBean.itemPath);
                    file.delete();
                    mediaList.remove(mediaBean);
                }
                mediaAdapter.notifyDataSetChanged();
            }
        });


    }

    private void initViews() {
        rgTitle = (RadioGroup) getView().findViewById(R.id.rg_title);
        rbPic = (RadioButton) getView().findViewById(R.id.rb_pic);
        rbVid = (RadioButton) getView().findViewById(R.id.rb_vid);
        rvView = (RecyclerView) getView().findViewById(R.id.rv_view);
        ivEdit = (ImageView) getView().findViewById(R.id.iv_edit);

        rvView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        mediaAdapter = new MediaAdapter(mediaList);
        mediaAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
            @Override
            public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                int span = mediaList.get(position).spanSize;
                return span;
            }
        });
        ((SimpleItemAnimator) rvView.getItemAnimator()).setSupportsChangeAnimations(false);//取消刷新item闪动画
        rvView.setAdapter(mediaAdapter);
    }

    public File[] getPictures(final String strPath) {
        File file = new File(strPath);
        File[] allfiles = file.listFiles();
        return allfiles;
    }

    public Bitmap getBitmap(String path, int dataType) {
        File mFile = new File(path);
        Bitmap bitmap = null;
        //若该文件存在
        if (mFile.exists()) {
            if (dataType == MediaBean.MEDIA_PIC) {
                bitmap = BitmapFactory.decodeFile(path);
            } else if (dataType == MediaBean.MEDIA_VID) {
                bitmap = getVideoThumbnail(path, 60, 60);
            }

            return bitmap;
        }
        return null;
    }

    public String getPaths(File fi) {
        if (fi.isFile()) {
            int idx = fi.getPath().lastIndexOf(".");
            if (idx <= 0) {
                return null;
            }
            String suffix = fi.getPath().substring(idx);
            if (suffix.toLowerCase().equals(".jpg") ||
                    suffix.toLowerCase().equals(".jpeg") ||
                    suffix.toLowerCase().equals(".bmp") ||
                    suffix.toLowerCase().equals(".png") ||
                    suffix.toLowerCase().equals(".mp4") ||
                    suffix.toLowerCase().equals(".gif")) {
                return fi.getPath();
            }
        }
        return null;
    }

    private Bitmap getVideoThumbnail(String videoPath, int width, int height) {
        Bitmap bitmap = null;
        bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, MediaStore.Video.Thumbnails.MINI_KIND);
//        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    public void openFiles(Context context, String filesPath, String type) {
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        File file = new File(filesPath);
        Uri contentUri = Uri.fromFile(file);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentUri = FileProvider.getUriForFile(context.getApplicationContext(), BuildConfig.APPLICATION_ID + ".fileprovider", file);
        }
        intent.setDataAndType(contentUri, type);
        getActivity().startActivity(intent);

    }

    public void showProgress(String msg) {
        if (!getActivity().isFinishing()) {
            dialog = new ProgressDialog(getContext());
            dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            dialog.setCanceledOnTouchOutside(false);
            dialog.setMessage(msg);
            dialog.show();
        }
    }

    /**
     * 进度条消失
     */
    public void dismissProgress() {
        if (dialog != null) {
            dialog.dismiss();
        }
    }

}
